package com.yzt.loginmodule.select;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.login.countryCode.GetZoneResponse;
import com.yzt.zhuju.network.entity.login.countryCode.ZoneInfo;
import com.yzt.zhuju.widget.LetterSideBar;
import com.yzt.loginmodule.R;
import com.yzt.loginmodule.select.adapter.CharacterParserUtil;
import com.yzt.loginmodule.select.adapter.CountryComparator;
import com.yzt.loginmodule.select.adapter.CountrySortAdapter;
import com.yzt.loginmodule.select.adapter.CountrySortModel;
import com.yzt.loginmodule.select.adapter.GetCountryNameSort;
import com.yzt.p_base.utils.NetworkUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * author : Irene
 * e-mail : 821970751@qq.com
 * date   : 2020/4/24 10:08
 * desc   :选择国家/地区
 */
@Route(path = RouterAccount.ACTIVITY_SELECT_ZONE)
public class SelectCountryAndZoneCodeActivity extends BaseActivity {

    @Autowired
    boolean isSelectCountry;

    @Autowired
    String extraCountry;

    private List<CountrySortModel> mAllCountryList;

    private EditText etSearch;

    private ListView countryLvCountryList;

    private ImageView imgClear;

    private CountrySortAdapter adapter;

    private LetterSideBar letterSideBar;

    private CountryComparator countryComparator;

    private GetCountryNameSort countryChangeUtil;

    private CharacterParserUtil characterParserUtil;

    private boolean isFooterAdded;

    private View viewFooter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_country_and_zone_code;
    }

    @Override
    public void installViews() {
        setFullScreen(true, R.color.transparent);
        viewFooter = getLayoutInflater().inflate(R.layout.layout_country_footer, null);

        findViewById(R.id.tv_cancel).setOnClickListener(v -> finish());

        etSearch = findViewById(R.id.country_et_search);
        countryLvCountryList = findViewById(R.id.country_lv_list);
        imgClear = findViewById(R.id.country_iv_cleartext);

        TextView dialog = findViewById(R.id.country_dialog);
        letterSideBar = findViewById(R.id.country_sidebar);
        letterSideBar.setTextView(dialog);

        mAllCountryList = new ArrayList<>();
        countryComparator = new CountryComparator();
        countryChangeUtil = new GetCountryNameSort();
        characterParserUtil = new CharacterParserUtil();

        // 将联系人进行排序，按照A~Z的顺序
        Collections.sort(mAllCountryList, countryComparator);
        adapter = new CountrySortAdapter(this, mAllCountryList, isSelectCountry);
        CountrySortModel countryModel = new CountrySortModel("中国", "+86", "*");
        if (extraCountry != null) {
            countryModel = new CountrySortModel(extraCountry, "", "*");
        }
        countryModel.sortLetters = "!";
        adapter.setDefaultCountry(countryModel);
        countryLvCountryList.setAdapter(adapter);

        setListener();
        loadData();
    }

    /****
     * 添加监听
     */
    private void setListener() {

        imgClear.setOnClickListener(v -> {
            etSearch.setText("");
            Collections.sort(mAllCountryList, countryComparator);
            adapter.updateListView(mAllCountryList);
        });

        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String searchContent = etSearch.getText().toString();
                if ("".equals(searchContent)) {
                    imgClear.setVisibility(View.INVISIBLE);
                } else {
                    imgClear.setVisibility(View.VISIBLE);
                }
                if (searchContent.length() > 0) {
                    // 按照输入内容进行匹配
                    ArrayList<CountrySortModel> filterList = (ArrayList<CountrySortModel>) countryChangeUtil.search(searchContent, mAllCountryList);
                    adapter.updateListView(filterList);
                } else {
                    adapter.updateListView(mAllCountryList);
                }
                countryLvCountryList.setSelection(0);
            }
        });

        // 右侧sideBar监听
        letterSideBar.setOnTouchingLetterChangedListener(s -> {
            // 该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                countryLvCountryList.setSelection(position);
            }
        });

        countryLvCountryList.setOnItemClickListener((adapterView, view, position, arg3) -> {
            if (mAllCountryList == null || mAllCountryList.isEmpty()) {
                return;
            }
            String countryName;
            String countryNumber;
            String searchContent = etSearch.getText().toString();

            if (searchContent.length() > 0) {
                // 按照输入内容进行匹配
                ArrayList<CountrySortModel> fileterList = (ArrayList<CountrySortModel>) countryChangeUtil.search(searchContent, mAllCountryList);
                if (fileterList == null || fileterList.isEmpty()) {
                    return;
                }

                if (position > 0 && position == fileterList.size()) {
                    position = position - 1;
                }

                CountrySortModel countrySortModel = fileterList.get(position);
                countryName = countrySortModel.countryName;
                countryNumber = countrySortModel.countryNumber;
            } else {
                if (mAllCountryList == null || mAllCountryList.isEmpty()) {
                    return;
                }
                if (mAllCountryList.size() == position) {
                    return;
                }
                // 点击后返回
                CountrySortModel sortModel = mAllCountryList.get(position);
                countryName = sortModel.countryName;
                countryNumber = sortModel.countryNumber;
            }
            Intent intent = new Intent();
            intent.putExtra("countryName", countryName);
            intent.putExtra("countryNumber", countryNumber);
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    private void loadData() {
        if (!NetworkUtils.isNetAvailable()) {
            showView(RXingUtils.getCountryAndZone());
            return;
        }
        showMProgress();
        BizLayer.getInstance().getAccountModule().getCountryOrZoneCode(new CountryAndZoneSubscriber());
    }

    private class CountryAndZoneSubscriber extends AresSubscriber<GetZoneResponse> {
        @Override
        protected void onSuccess(GetZoneResponse mGetZoneResponse) {

            if (mGetZoneResponse != null) {
                RXingUtils.saveCountryAndZone(mGetZoneResponse);
            }
            showView(mGetZoneResponse);
        }

        @Override
        protected void onError(int code, String info) {
            super.onError(code, info);
            showView(RXingUtils.getCountryAndZone());
        }

        @Override
        protected void onFinallyEnd() {
            super.onFinallyEnd();
            closeProgress();
        }
    }

    private void showView(GetZoneResponse mGetZoneResponse) {

        if (mGetZoneResponse == null) {
            return;
        }
        List<ZoneInfo> zoneInfoList = new ArrayList<>();
        for (Map.Entry<String, List<ZoneInfo>> entry : mGetZoneResponse.getAreaList().entrySet()) {
            zoneInfoList.addAll(entry.getValue());
        }
        for (ZoneInfo zoneInfo : zoneInfoList) {
            String countryName = zoneInfo.getNames();
            String countryNumber = "+" + zoneInfo.getSid();
            String countrySortKey = characterParserUtil.getSelling(countryName);
            CountrySortModel countrySortModel = new CountrySortModel(countryName,
                    countryNumber, countrySortKey);
            String sortLetter = countryChangeUtil.getSortLetterBySortKey(countrySortKey);
            if (sortLetter == null) {
                sortLetter = countryChangeUtil.getSortLetterBySortKey(countryName);
            }
            countrySortModel.sortLetters = sortLetter;
            mAllCountryList.add(countrySortModel);
        }
        Collections.sort(mAllCountryList, countryComparator);
        adapter.updateListView(mAllCountryList);
        if (!isFooterAdded) {
            isFooterAdded = true;
            countryLvCountryList.addFooterView(viewFooter);
        }
    }
}
